<template>
    <div>
        <el-main>
            <!-- 查询表单 -->
            <el-form :inline="true" :model="customerModle" size="small" label-width="100px">
                <el-form-item>
                    <el-input v-model="customerModle.name" placeholder="请输入客户姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="customerModle.tel" placeholder="请输入客户电话"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="customerModle.idNum" placeholder="请输入客户身份证"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input-number v-model="customerModle.lowAge" placeholder="年龄低值"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-input-number v-model="customerModle.highAge" placeholder="年龄高值"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="customerModle.gender" placeholder="请选择性别">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch" icon="el-icon-search">查询</el-button>
                    <el-button type="warning" @click="resetForm" icon="el-icon-refresh">重置</el-button>
                    <el-button type="success" @click="handlecreate" icon="el-icon-plus">新增</el-button>
                    <el-button type="danger" @click="deleteBatch" icon="el-icon-delete">删除选中</el-button>
                </el-form-item>
            </el-form>
            <el-divider></el-divider>
            <!-- 数据表格 -->
            <el-table :data="tableData" border stripe style="width: 100%;margin-bottom: 20px;"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" width="60">
                    <template slot-scope="scope">{{ (start - 1) * size + scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column label="客户姓名" prop="name"></el-table-column>
                <el-table-column label="身份证号" prop="idNum"></el-table-column>
                <el-table-column label="客户年龄" prop="age"></el-table-column>
                <el-table-column label="联系电话" prop="tel"></el-table-column>
                <el-table-column label="客户性别" prop="gender">
                    <template slot-scope="scope">{{ scope.row.gender == 1 ? "男" : "女" }}</template>
                </el-table-column>
                <el-table-column label="出生日期" prop="birthday"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
                            icon="el-icon-edit">编辑</el-button>
                        <el-button type="danger" size="mini" @click="handleDelete(scope.row)"
                            icon="el-icon-delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table> 
            <!-- 分页 -->
            <el-pagination @current-change="search" :current-page="start" :page-size="size"
                layout="total,  prev, pager, next, jumper" :total="total"></el-pagination>
            <!-- 新增与添加对话框  -->
            <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%">
                <el-form :model="saveCustomer" :rules="rules" ref="form" label-width="80px">
                    <el-form-item label="客户姓名" prop="name">
                        <el-input v-model="saveCustomer.name"></el-input>
                    </el-form-item>
                    <el-form-item label="身份证号" prop="idNum">
                        <el-input v-model="saveCustomer.idNum" @change="setCustomerInfo"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="tel">
                        <el-input v-model="saveCustomer.tel" type="tel"></el-input>
                    </el-form-item>
                    <el-form-item label="客户年龄" prop="age">
                        <el-input v-model="saveCustomer.age" :readonly="true"></el-input>
                    </el-form-item>
                    <el-form-item label="客户性别" prop="gender">
                        <el-radio-group v-model="saveCustomer.gender">
                            <el-radio-button :label="1" disabled>男</el-radio-button>
                            <el-radio-button :label="0" disabled>女</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="出生日期" prop="birthday">
                        <el-date-picker v-model="saveCustomer.birthday" type="date" placeholder="选择日期"
                            value-format="yyyy-MM-dd" :readonly="true"></el-date-picker>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确
                        定</el-button>
                </div>
            </el-dialog>
        </el-main>
    </div>
</template>
<script>
import customerUtil  from '@/api/customer';

export default{
    data(){
        return{
            customerModle:{},
            start:1,
            size:5,
            total:0,
            tableData:[],
            titleMap:{
                create:'新增客户',
                update:'修改客户'
            },
            dialogStatus:'create',
            dialogFormVisible:false,
            saveCustomer:{},
            rules:{
                name:[
                    {required:true,message:'请输入客户名称',trigger:'blur'}
                ],
                idNum:[
                    {required:true,message:'请输入身份证号',trigger:'blur'},
                    {min:18,max:18,message:'身份证号长度为18位',trigger:'blur'}
                ],
                tel:[
                    {required:true,message:'请输入客户电话',trigger:'blur'},
                    {min:11,max:11,message:'客户电话长度为11位',trigger:'blur'}
                ],
            }

        }
    },
    created(){
        this.search();
    },
    methods:{
        async search(start=1){
            this.start=start;
            const res=await customerUtil.search(this.start,this.size,this.customerModle);
            if(res.success){
                this.tableData=res.data.records;
                this.total=res.data.total;
            }
        },
        handleSearch(){
            this.search();
        },
        handlecreate(){
            this.dialogStatus='create';
            this.saveCustomer={};
            this.dialogFormVisible=true;
            this.$nextTick(()=>{
                this.$refs['form'].clearValidate();
            });
        },
        resetForm(){
            this.tableData=[];
            this.customerModle={};
            this.search();
        },
        deleteBatch(){
            if(this.multipleSelection.length==0){
                this.$message({
                    type:'warning',
                    message:'请选择要删除的数据!'
                });
                return;
            }else{
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(()=>{
                    customerUtil.delete(this.multipleSelection).then(res=>{
                        if(res.success){
                            this.$message({
                                type:'success',
                                message:'删除成功!'
                            });
                            this.search();
                        }
                    })
                })
            }
        },
        handleSelectionChange(val){
            this.multipleSelection=[];
            val.forEach(element => {
                this.multipleSelection.push(element.id)
            });
        },
        handleUpdate(row){
            this.saveCustomer=Object.assign({},row);
            this.dialogStatus='update';
            this.dialogFormVisible=true;
            this.$nextTick(()=>{
                this.$refs['form'].clearValidate();
            });
        },
        handleDelete(row){
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(()=>{
                customerUtil.delete(row.id).then(res=>{
                    if(res.success){
                        this.$message({
                            type:'success',
                            message:'删除成功!'
                        })
                        this.search();
                    }
                })
            })
        },
        setCustomerInfo(val){
            // 处理性别
            const sex = val.charAt(val.length-2);
            this.saveCustomer.gender = sex%2;

            // 处理年龄
            // 获取用户身份证上的出生日期
            const birthday = val.substring(6,14);
            const birthDate = new Date(birthday.substring(0,4),birthday.substring(4,6)-1,birthday.substring(6,8))
            // 获取当前系统时间
            let now = new Date();
            let timeDiff = Math.abs(now.getTime() - birthDate.getTime());
            if(timeDiff>0){
                // 获取年龄
                this.saveCustomer.age = Math.floor(timeDiff / (24 * 3600 * 1000 * 365));
                this.saveCustomer.birthday = birthDate;
            }
            this.$forceUpdate();
        },
        createData(){
            this.$refs['form'].validate(async valid => {
                if (!valid) {
                    return false;
                } else {
                    const res = await customerUtil.add(this.saveCustomer);
                    if (res.success) {
                        this.$message({
                            type: 'success',
                            message: '新增成功!'
                        });
                        //将当前对话框关闭
                        this.dialogFormVisible = false;
                       this.search();
                    }
                }
            });
        },
        updateData(){
            this.$refs['form'].validate(async valid => {
                if (!valid) {
                    return false;
                } else {
                    const res = await customerUtil.update(this.saveCustomer);
                    if (res.success) {
                        this.$message({
                            type: 'success',
                            message: '修改成功!'
                        });
                        this.dialogFormVisible = false;
                        this.search();
                    }
                }
            });
        },
    }
}

</script>
<style></style>